require('dotenv').config();

const express = require('express');
const cors = require('cors');
const path = require('path');

// 工具和中间件
const logger = require('./utils/logger');
const { testConnection } = require('./config/db');
const requestLogger = require('./middleware/requestLogger');
const { generalLimiter } = require('./middleware/rateLimiter');
const { securityHeaders, sqlInjectionProtection, xssProtection } = require('./middleware/security');
const { errorHandler, notFoundHandler, handleUncaughtException, handleUnhandledRejection } = require('./middleware/errorHandler');

// 路由引入
const videoRoutes = require('./routes/video');
const categoryRoutes = require('./routes/category');
const userOperateRoutes = require('./routes/userOperate');
const commentRoutes = require('./routes/comment');
const adminRoutes = require('./routes/admin');
const feedbackRoutes = require('./routes/feedback');
const healthRoutes = require('./routes/health');
const logRoutes = require('./routes/log');
const userRoutes = require('./routes/user');

const app = express();
const PORT = process.env.PORT || 3000;

// 注册进程异常处理
handleUncaughtException();
handleUnhandledRejection();

// 基础中间件
app.use(cors({
  origin: process.env.CORS_ORIGIN || '*',
  credentials: true
}));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// 安全中间件
app.use(securityHeaders);
app.use(sqlInjectionProtection);
app.use(xssProtection);

// 请求日志
app.use(requestLogger);

// 限流（应用于所有路由，可通过环境变量禁用）
if (process.env.DISABLE_RATE_LIMIT !== 'true') {
  app.use(generalLimiter);
  logger.info('限流已启用', {
    window: process.env.RATE_LIMIT_WINDOW_MS || '自动配置',
    maxRequests: process.env.RATE_LIMIT_MAX_REQUESTS || '自动配置'
  });
} else {
  logger.warn('⚠️  限流已禁用 - 仅建议在开发环境使用');
}

// 静态资源托管
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 根路由
app.get('/', (req, res) => {
  res.json({ 
    message: '欢迎使用乡音戏苑后端服务',
    version: '2.0.0',
    environment: process.env.NODE_ENV || 'development',
    timestamp: Date.now()
  });
});

// 健康检查和监控路由
app.use('/api', healthRoutes);

// API 路由
app.use('/api/videos', videoRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/user', userOperateRoutes);
app.use('/api/comments', commentRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/feedbacks', feedbackRoutes);
app.use('/api/logs', logRoutes);
app.use('/api/users', userRoutes);  // 用户注册登录路由

// 404 处理
app.use(notFoundHandler);

// 错误处理中间件（必须放在最后）
app.use(errorHandler);

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接
    logger.info('正在测试数据库连接...');
    await testConnection();
    
    // 启动服务器
    app.listen(PORT, () => {
      logger.info(`乡音戏苑后端服务启动成功`, {
        port: PORT,
        environment: process.env.NODE_ENV || 'development',
        nodeVersion: process.version
      });
      
      console.log(`\n========================================`);
      console.log(`  乡音戏苑后端服务已启动`);
      console.log(`  端口: ${PORT}`);
      console.log(`  环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`  健康检查: http://localhost:${PORT}/api/health`);
      console.log(`  系统状态: http://localhost:${PORT}/api/status`);
      console.log(`========================================\n`);
    });
  } catch (error) {
    logger.error('服务器启动失败', {
      error: error.message,
      stack: error.stack
    });
    process.exit(1);
  }
};

// 优雅关闭
const gracefulShutdown = (signal) => {
  logger.info(`收到 ${signal} 信号，开始优雅关闭服务器...`);
  
  // 这里可以添加清理工作
  // 例如：关闭数据库连接、完成待处理的请求等
  
  process.exit(0);
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// 启动服务器
startServer();

module.exports = app;